//
//  TLSearchBar.m
//  Coding_iOS
//
//  Created by taolei-mac on 2017/12/27.
//  Copyright © 2017年 com.lianchuan. All rights reserved.
//

#import "TLSearchBar.h"

@interface TLSearchBar ()

@property (nonatomic, assign) CGFloat placeholderWidth;

@property (nonatomic, weak) UILabel *placeholderLabel;

@property (nonatomic, weak) UIImageView *searchBarIcon;

@end

// icon宽度
static CGFloat const searchIconW = 13.0;
// icon与placeholder间距
// static CGFloat const iconSpacing = 5.0;
// 占位文字的字体大小
static CGFloat const placeHolderFont = 15.0;

@implementation TLSearchBar

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setBackgroundColor:[UIColor whiteColor]];
        self.textColor = [UIColor colorWithHexString:@"0x76808E"];
        self.borderStyle = UITextBorderStyleNone;
        self.layer.cornerRadius = 2.0f;
        self.layer.masksToBounds = YES;
    
        UILabel *placeholderLabel = [[UILabel alloc] init];
        placeholderLabel.textColor = [UIColor colorWithHexString:@"0x76808E"];
        placeholderLabel.font = [UIFont systemFontOfSize:placeHolderFont];
        [self addSubview:placeholderLabel];
        self.placeholderLabel = placeholderLabel;
        
        UIImageView *searchIcon = [[UIImageView alloc] initWithImage:[UIImage originImageWithName:@"icon_search_searchbar"]];
        searchIcon.frame = CGRectMake(placeholderLabel.x - 10, 8.5, searchIconW, searchIconW);
        [self addSubview:searchIcon];
        self.searchBarIcon = searchIcon;
        
    }
    return self;
}

- (void)setPlaceholderStr:(NSString *)placeholderStr
{
    _placeholderStr = [placeholderStr copy];

    _placeholderLabel.text = placeholderStr;
    [_placeholderLabel sizeToFit];
}

- (UIButton *)scanBtn
{
    if (!_scanBtn) {
        _scanBtn = [UIButton new];
        [_scanBtn setImage:[UIImage imageNamed:@"button_scan"] forState:UIControlStateNormal];
        [self addSubview:_scanBtn];
        [_scanBtn mas_makeConstraints:^(MASConstraintMaker *make) {

            make.size.mas_equalTo(CGSizeMake(50, 30));
            make.centerY.equalTo(self);
            make.right.equalTo(self);
        }];
    }
    return _scanBtn;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    self.searchBarIcon.frame = CGRectMake(self.width * 0.5 - 25, (self.height - self.searchBarIcon.image.size.height) * 0.5, self.searchBarIcon.image.size.width, self.searchBarIcon.image.size.height);
    self.placeholderLabel.frame = CGRectMake(CGRectGetMaxX(self.searchBarIcon.frame) + 10, (self.height - 20) * 0.5, self.placeholderLabel.width, 20);
}

//- (CGFloat)placeholderWidth
//{
//    if (!_placeholderWidth) {
//        _placeholderWidth = [self.placeholderStr getWidthWithFont:[UIFont systemFontOfSize:placeHolderFont] constrainedToSize:CGSizeMake(MAXFLOAT, 45)] + iconSpacing + searchIconW;
//    }
//    return _placeholderWidth;
//}

@end
